package com.zone.domain.common.factory;

import com.zone.domain.common.context.SpringContextHolder;
import com.zone.types.exception.BizException;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.context.ApplicationContext;

import java.util.*;

/**
 * @author: zongzi
 * @description: 简单工厂
 * @date: 2025/3/13
 */
public class SimpleFactory<T> {
    // spring 应用上下文Application
    private static ApplicationContext CONTEXT = SpringContextHolder.getApplicationContext();
    // 处理器类型
    private final Class<T> handlerClazz;
    // 处理器映射表
    private final Map<String, T> handlerMap = new HashMap<>();

    public static void setApplicationContext(ApplicationContext applicationContext) {
        CONTEXT = applicationContext;
    }

    public SimpleFactory(Class<T> handlerClazz) {
        this.handlerClazz = handlerClazz;
        Map<String, T> handlerBeanMap = CONTEXT.getBeansOfType(handlerClazz);
        for (String beanName : handlerBeanMap.keySet()) {
            T bean = handlerBeanMap.get(beanName);
            if (!(bean instanceof FactoryName)) {
                Class<?> clazz = bean.getClass();
                String errorMsg = String.format("class name [%s] not implement FactoryName", clazz.getSimpleName());
                throw new BizException(errorMsg);
            }
            FactoryName factoryName = (FactoryName) bean;
            // 判断factoryName是否已经注册
            String name = factoryName.getName();
            Set<String> nameSet = handlerMap.keySet();
            if (nameSet.contains(name)) {
                String joinNames = String.join(",", nameSet);
                String errorMsg = String.format("factoryName not repeat, repeat name [%s], already register names [%s]", name, joinNames);
                throw new BizException(errorMsg);
            }
            handlerMap.put(name, bean);
        }
    }

    public T newInstance(String name) {
        return handlerMap.get(name);
    }

    public Class<T> getHandlerClazz() {
        return handlerClazz;
    }

    public List<T> getAllHandler() {
        return new ArrayList<>(handlerMap.values());
    }

    public boolean isExistHandler() {
        return CollectionUtils.isNotEmpty(handlerMap.values());
    }
}
